import tip from './tip'
import { isLogin } from '@/utils/auth.js'
import md5 from "../components/encryption"
import { randomString } from './index';

// 测试
export const base_url = 'http://meet.metatmt.com/'
//正式
//export const base_url = 'https://api.metatmt.com/'

export const socket_url = ''

export const version = '1.0.44'

export const uniRequest = async (params={},url)=> {
	let query = params.query || {};
  query.version = version;
  query.lang = uni.getStorageSync('language') ||'en';
  query.platform = uni.getStorageSync('platform') || 'web';
  query.timestamp = new Date().getTime();
  query.nonce = randomString(8);
  query.sign = md5(query.timestamp + query.nonce + "XhTVLuod7sNCQbFZGMD8vl6ke3mnSRHpi1yWzrcwqgPIUY5Oj2t9KEfa4ABxJ0");
  query.unique_code = uni.getStorageSync('unique_code') || '';

  // query.lang = vue._i18n.locale
  let header =  { 'Content-Type': 'application/json' }
  let token = uni.getStorageSync('token');
  if (token) {
    header.Authorization = 'Bearer ' + token
  }
  if (params.header) {
    header = {...header, ...params.header}
  }
  // 加载效果
  if (params.loading) {
    tip.loading(params.loading);
  }
  // 发起请求
  let response = await uni.request({
      url: url,
      method: params.method || 'GET',
      data: query,
      header: header,
  })
  if (params.loading) {
    tip.loaded();
  }
  // 响应数据
  const res = response[1].data
  if (res.code === -2) {
    return Promise.reject(res);
  }
  if (res.code === 401) {
    console.log("=========401401401401401401===========");
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
    // isLogin()
  }
  return res;
};

export const uniRequestNoLoading = async (params,url)=> {
  // 添加token请求头
	let data = params.query || {};
  let header =  { 'Content-Type': 'application/json' }
  let token = uni.getStorageSync('token');
  if (token) {
    header.Authorization = 'Bearer ' + token
  }
  if (params.header) {
    header = {...header, ...params.header}
  }
  // 发起请求
  let response = await uni.request({
      url: url,
      method: params.method || 'GET',
      data: params.query,
      header: header,
  })
  // 响应数据
  const res = response[1].data
  if (res.code !== 0) {
    tip.defaults(res.msg || '请求失败，请重试')
    // 401清除登录信息
    if (res.code === 401) {
      uni.removeStorageSync('token')
    }
    // 抛出异常，阻止调用者继续执行，调用者可通过.catch抓取该异常后继续执行
    return Promise.reject(res);
  }
  return res;
};


